<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background: #f90!important;
            cursor: move;
        }

        .box1 {
            width: 500px;
            height: 500px;
            border: 2px solid palevioletred;
            margin-left: 300px;
            position: relative;
        }

        .leaver {
            width: 500px;
            height: 500px;
            background: rgba(0, 0, 0, .3);
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>

<body>
    <div class="box" draggable="true"></div>
    <div class="box1"></div>
</body>
<script>
    window.onload = function () {
        // 1.给元素设置draggable="true"为可以拖动元素
        var boxDom = document.querySelector('.box');
        // 2.拖动的元素
        boxDom.addEventListener('dragstart', (e) => {
            // console.log(e);
            // 使用dataTransfer.setData携带数据
            e.dataTransfer.setData('className', e.target.className);
        })

        var box1Dom = document.querySelector('.box1');
        box1Dom.addEventListener('dragenter',(e)=>{
            e.preventDefault();
            box1Dom.className = 'box1 leaver';
        })
        // 进入存放区域的动作
        box1Dom.addEventListener('dragover', (e) => {
            e.preventDefault();
        })
        // 在存放区域放下的动作
        box1Dom.addEventListener('drop', (e) => {
            e.preventDefault();
            // console.log('==>',e);
            var className = e.dataTransfer.getData('className');
            var newBox = document.createElement('div');
            newBox.className = className;
            box1Dom.appendChild(newBox);
            box1Dom.className = 'box1';
        })
        // 监听移开后的事件
        box1Dom.addEventListener('dragleave', (e) => {
            e.preventDefault();
            box1Dom.className = 'box1';
        })
    }
</script>

</html>